package com.jfinal.bbsapp.video;
import org.apache.log4j.Logger;
import com.jfinal.bbsapp.common.kit.CommonUtils;
import com.jfinal.bbsapp.common.kit.MyAnnotation;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.bbsapp.common.kit.SnowFlake;

@MyAnnotation(memo="视频播放业务类")
public class VideoService {
	
	private final Logger logger = Logger.getLogger(VideoService.class);
	private static SnowFlake snowFlake = new SnowFlake(1, 1);
	
	@MyAnnotation(memo="当前章节是否收藏过")
	public Ret iscollect(String token,String chapterid) {
		try {
			String userid=CommonUtils.getuseridbytoken(token);
			Record rec = Db.findFirst("select collectid from c_user_collect where cuserid=? and chapterid=?",userid,chapterid);
			String iscollect="0";
			if(rec != null){
				iscollect="1";
			}
			String isfirst = "1";int lastwatchtime = 0;
			Record watchrec = Db.findFirst("select recordid,watchtime,watchrate,isfirst from c_user_record "
				+ "where cuserid=? and chapterid=? order by ctime desc",userid,chapterid);
			if(watchrec != null){
				if(watchrec.getStr("isfirst").equals("1")) {
					if(watchrec.getDouble("watchrate") < 100.00) {
						lastwatchtime = watchrec.getInt("watchtime");
					}else {
						isfirst="0";
					}
				}else {
					isfirst="0";
				}
			}
			return Ret.ok("data",iscollect).set("isfirst",isfirst).set("lastwatchtime",lastwatchtime).set("code", 20000);
		} catch (Exception e) {
			logger.error("Exception:" , e);
			return Ret.fail("系统异常请稍后重试").set("code", 50000);
		}
	}
	
	@MyAnnotation(memo="收藏添加")
	public Ret collectadd(String token,String chapterid) {
		try {
			String userid=CommonUtils.getuseridbytoken(token);
			Record rec = Db.findFirst("select collectid from c_user_collect where cuserid=? and chapterid=?",userid,chapterid);
			if(rec != null){
				return Ret.fail("本章节已收藏过").set("code", 51000);
			}
			Db.tx(() -> {
				Db.update("insert into c_user_collect(collectid,cuserid,chapterid,ctime)values(?,?,?,?)",snowFlake.nextId(),userid,chapterid,System.currentTimeMillis());
				return true;
			});
			return Ret.ok("提交成功").set("code", 20000);
		} catch (Exception e) {
			logger.error("Exception:" , e);
			return Ret.fail("系统异常请稍后重试").set("code", 50000);
		}
	}
	
	@MyAnnotation(memo="收藏删除")
	public Ret collectdel(String token,String chapterid) {
		try {
			String userid=CommonUtils.getuseridbytoken(token);
			Db.tx(() -> {
				Db.update("delete from c_user_collect where cuserid=? and chapterid=?",userid,chapterid);
				return true;
			});
			return Ret.ok("提交成功").set("code", 20000);
		} catch (Exception e) {
			logger.error("Exception:" , e);
			return Ret.fail("系统异常请稍后重试").set("code", 50000);
		}
	}
	
	@MyAnnotation(memo="我的课程收藏分页列表")
	public Ret collectplist(String token,int pagecurrent, int pagesize) {
		try {
			String userid=CommonUtils.getuseridbytoken(token);
			String querySql = "select cast(a.chapterid as char) chapterid,cast(a.courseid as char) courseid,cast(b.collectid as char) collectid,a.chaptername,a.img,a.videourl,a.sortno";	
			StringBuilder sql = new StringBuilder();
			sql.append(" from c_chapter a join c_user_collect b on a.chapterid=b.chapterid");
			sql.append(" where b.cuserid="+userid);
			sql.append(" order by a.sortno asc");
			Page<Record> page = Db.paginate(pagecurrent, pagesize, querySql, sql.toString());
			return Ret.ok("data", page).set("code", 20000);
		} catch (Exception e) {
			logger.error("------Exception------", e);
			return Ret.fail("系统异常").set("code", 50000);
		}
	}
	
	@MyAnnotation(memo="课程卡核销")
	public Ret issure(String token,String courseid,String cardno) {
		try {
			Record cardrec = Db.findFirst("select cardid,agentid,agentname,isuse,opencourseidstr,flag from c_course_card where cardno=?",cardno);
			if(cardrec == null){
				return Ret.fail("课程卡不存在").set("code", 51000);
			}else{
				if(cardrec.getStr("flag").contains("1")){
					return Ret.fail("课程卡已禁用").set("code", 51000);
				}
				if(cardrec.getStr("isuse").contains("1")){
					return Ret.fail("课程卡已核销使用过").set("code", 51000);
				}
				if(!cardrec.getStr("opencourseidstr").contains(courseid)){
					return Ret.fail("课程卡不支持开通此课程").set("code", 51000);
				}
			}
			Record courserec = Db.findFirst("select coursename from c_course where courseid=?",courseid);
			String userid=CommonUtils.getuseridbytoken(token);
			Record urec = Db.findFirst("select mobile,nickname from c_user where userid=?",userid);
			Db.tx(() -> {
				Db.update("insert into c_card_sure(sureid,cuserid,mobile,nickname,cardid,cardno,courseid,coursename,agentid,agentname,ctime)values(?,?,?,?,?,?,?,?,?,?,?)",
				snowFlake.nextId(),userid,urec.getStr("mobile"),urec.getStr("nickname"),cardrec.getLong("cardid"),cardno,courseid,courserec.getStr("coursename"),
				cardrec.getLong("agentid"),cardrec.getStr("agentname"),System.currentTimeMillis());
				
				Db.update("update c_course_card set isuse='1',utime=? where cardid=?",System.currentTimeMillis(),cardrec.getLong("cardid"));
				Db.update("update c_user set agentid=? where userid=?",cardrec.getLong("agentid"),userid);
				return true;
			});
			return Ret.ok("提交成功").set("code", 20000);
		} catch (Exception e) {
			logger.error("Exception:" , e);
			return Ret.fail("系统异常请稍后重试").set("code", 50000);
		}
	}
	
	@MyAnnotation(memo="校验课程是否已开卡与是否要人脸核身")
	public Ret coursecheck(String token,String courseid) {
		try {
			String userid=CommonUtils.getuseridbytoken(token);
			Record rec = Db.findFirst("select sureid from c_card_sure where courseid=? and cuserid=?",courseid,userid);
			if(rec == null){
				return Ret.fail("课程未开卡").set("ischeck", "0").set("code", 51000);
			}else{//已开卡判断是否需要人脸核身
				Record urec = Db.findFirst("select ischeck,checktime from c_user where userid=?",userid);
				if(urec.getStr("ischeck").equals("0")){//当前人是否需要人脸核身
					return Ret.ok("课程已开卡").set("ischeck", "0").set("code", 20000);	
				}else {
					Record configrec = Db.findFirst("select setval from sys_config where configcode='ischeckface'");
					if(configrec.getStr("setval").equals("0")){//系统是否开启人脸核身
						return Ret.ok("课程已开卡").set("ischeck", "0").set("code", 20000);	
					}else {
						if(urec.getLong("checktime") <= 0) {
							return Ret.ok("课程已开卡").set("ischeck", "1").set("code", 20000);
						}else {
							Record checktimerec = Db.findFirst("select setval from sys_config where configcode='checkfacetime'");
							if(((checktimerec.getLong("setval")*60*60*1000 + urec.getLong("checktime")) < System.currentTimeMillis())){
								return Ret.ok("课程已开卡").set("ischeck", "1").set("code", 20000);	
							}else {
								return Ret.ok("课程已开卡").set("ischeck", "0").set("code", 20000);	
							}
						}
					}
				}	
			}	
		} catch (Exception e) {
			logger.error("Exception:" , e);
			return Ret.fail("系统异常请稍后重试").set("code", 50000);
		}
	}
	
	@MyAnnotation(memo="添加观看记录")
	public Ret recordadd(String token,String chapterid,String watchtime) {
		try {
			String userid=CommonUtils.getuseridbytoken(token);
			Record urec = Db.findFirst("select nickname,mobile from c_user where userid=?",userid);
			
			Record chapterrec = Db.findFirst("select courseid,chaptername,classhour,sortno from c_chapter where chapterid=?",chapterid);
			Record courserec = Db.findFirst("select coursename from c_course where courseid=?",chapterrec.getStr("courseid"));
			long agentid=0;String agentname="";
			Record surerec = Db.findFirst("select agentid,agentname from c_card_sure where cuserid=?",userid);
			if(surerec != null) {
				agentid=surerec.getLong("agentid");agentname=surerec.getStr("agentname");
			}
			
			
			/*
			//前端传毫秒转为秒(/1000),章节课程时间用秒存储数据库，观看记录也是秒
			double userwatchtime = Double.valueOf(watchtime) / 1000;
			String isfirst = "0";
		    
			
			//第一遍学习观看是否完成100%判断
			Record watchrec = Db.findFirst("select recordid,watchrate,isfirst,firstwatchtime from c_user_record "
				+ "where cuserid=? and chapterid=? order by ctime desc",userid,chapterid);
			if(watchrec != null ) {
				if(watchrec.getStr("isfirst").equals("1") && watchrec.getDouble("watchrate") < 100.00) {
					userwatchtime = userwatchtime + watchrec.getDouble("firstwatchtime");
					isfirst = "1";	
				}
			}else {
				isfirst = "1";	
			}
			
			//观看进度转百分比
			double rate = (userwatchtime / chapterrec.getDouble("classhour")) * 100;
			if(rate > 100) {
				rate = 100;
			}
			String strrate = String.format("%.2f", rate);
			
			Db.update("insert into c_user_record(recordid,cuserid,mobile,nickname,agentid,agentname,"
			+ "courseid,coursename,chapterid,chaptersortno,chaptername,watchtime,watchrate,isfirst,firstwatchtime,ctime)"
			+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
			String.valueOf(snowFlake.nextId()),userid,urec.getStr("mobile"),urec.getStr("nickname"),agentid,agentname,
			chapterrec.getLong("courseid"),courserec.getStr("coursename"),chapterid,chapterrec.getInt("sortno"),chapterrec.getStr("chaptername"),
			Double.valueOf(watchtime)/1000,strrate,isfirst,userwatchtime,System.currentTimeMillis());
			*/
			
			
			double userwatchtime = Double.valueOf(watchtime) / 1000;
			double rate = (userwatchtime / chapterrec.getDouble("classhour")) * 100;
			if(rate > 100) {
				rate = 100;
			}
			String strrate = String.format("%.2f", rate);
		    
			//第一次观看是否100%判断
			Record watchrec = Db.findFirst("select recordid,watchtime,watchrate,isfirst from c_user_record "
					+ "where cuserid=? and chapterid=? order by ctime desc",userid,chapterid);
			if(watchrec != null ) {
				if(watchrec.getStr("isfirst").equals("1")) {
					if(watchrec.getDouble("watchrate") < 100.00) {
						if(userwatchtime > watchrec.getDouble("watchtime")){
							Db.update("update c_user_record set watchtime=?,watchrate=? where recordid=?",Double.valueOf(watchtime)/1000,strrate,watchrec.getStr("recordid"));	
						}
					}else {
						Db.update("insert into c_user_record(recordid,cuserid,mobile,nickname,agentid,agentname,courseid,coursename,chapterid,chaptersortno,chaptername,watchtime,watchrate,isfirst,ctime)"
						+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",String.valueOf(snowFlake.nextId()),userid,urec.getStr("mobile"),urec.getStr("nickname"),agentid,agentname,
						chapterrec.getLong("courseid"),courserec.getStr("coursename"),chapterid,chapterrec.getInt("sortno"),chapterrec.getStr("chaptername"),
						Double.valueOf(watchtime)/1000,strrate,"0",System.currentTimeMillis());	
					}
				}else {
					Db.update("insert into c_user_record(recordid,cuserid,mobile,nickname,agentid,agentname,courseid,coursename,chapterid,chaptersortno,chaptername,watchtime,watchrate,isfirst,ctime)"
					+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",String.valueOf(snowFlake.nextId()),userid,urec.getStr("mobile"),urec.getStr("nickname"),agentid,agentname,
					chapterrec.getLong("courseid"),courserec.getStr("coursename"),chapterid,chapterrec.getInt("sortno"),chapterrec.getStr("chaptername"),
					Double.valueOf(watchtime)/1000,strrate,"0",System.currentTimeMillis());	
				}
			}else {
				Db.update("insert into c_user_record(recordid,cuserid,mobile,nickname,agentid,agentname,courseid,coursename,chapterid,chaptersortno,chaptername,watchtime,watchrate,isfirst,ctime)"
					+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",String.valueOf(snowFlake.nextId()),userid,urec.getStr("mobile"),urec.getStr("nickname"),agentid,agentname,
					chapterrec.getLong("courseid"),courserec.getStr("coursename"),chapterid,chapterrec.getInt("sortno"),chapterrec.getStr("chaptername"),
					Double.valueOf(watchtime)/1000,strrate,"1",System.currentTimeMillis());
			}
			
			
			
			return Ret.ok("提交成功").set("code", 20000);
		} catch (Exception e) {
			logger.error("Exception:" , e);
			return Ret.fail("系统异常请稍后重试").set("code", 50000);
		}
	}
	
	@MyAnnotation(memo="观看记录提交长度")
	public Ret recordstartnum(String token) {
		try {
			Record rec = Db.findFirst("select setval from sys_config where configcode='recordstartnum'");
			return Ret.ok("data", rec.getStr("setval")).set("code", 20000);
		} catch (Exception e) {
			logger.error("Exception:" , e);
			return Ret.fail("系统异常请稍后重试").set("code", 50000);
		}
	}
	
}
